package handler

import (
	"context"
	"video_server/basic/config"
	"video_server/basic/model"
	"video_server/basic/proto/video"
)

type Server struct {
	video.UnimplementedVideoServerServer
}

func (s *Server) UserDetails(_ context.Context, req *video.UserDetailsReq) (*video.UserDetailsResp, error) {
	var User model.Users
	err := config.DB.Where("id=?", req.UserId).Find(&User).Error
	if err != nil {
		return nil, err
	}
	users := []*video.UserList{}
	users = append(users, &video.UserList{
		Name:              User.Name,
		Url:               User.Url,
		Account:           User.Account,
		BriefIntroduction: User.BriefIntroduction,
		Address:           User.Address,
	},
	)
	return &video.UserDetailsResp{List: users}, nil
}
func (s *Server) VideoAdd(_ context.Context, req *video.VideoAddReq) (*video.VideoAddResp, error) {
	Video1 := model.Videos{
		UserId:             int64(req.UserId),
		Url:                req.VideoString,
		VideoType:          1,
		PushClassification: 2,
		Recommend:          2,
		PlayCount:          0,
	}
	err := config.DB.Create(&Video1).Error
	if err != nil {
		return nil, err
	}
	return &video.VideoAddResp{Success: true}, nil
}
func (s *Server) VideoList(_ context.Context, req *video.VideoListReq) (*video.VideoListResp, error) {
	var Video []model.Videos
	err := config.DB.Where("user_id=?", req.UserId).Where("video_type=?", req.Type).Find(&Video).Error
	if err != nil {
		return nil, err
	}
	videos := []*video.VideoList{}
	for _, m := range Video {
		videos = append(videos, &video.VideoList{
			UserId: int32(m.UserId),
			Url:    m.Url,
		})
	}
	return &video.VideoListResp{List: videos}, nil
}
func (s *Server) VideosList(_ context.Context, req *video.VideosListReq) (*video.VideoListResp, error) {
	var Video []model.Videos
	page := req.Page
	if page <= 0 {
		page = 1
	}

	pageSize := req.PageSize
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	err := config.DB.Offset(int(offset)).Limit(int(pageSize)).Where("video_type=?", 4).Find(&Video).Error

	if err != nil {
		return nil, err
	}
	videos := []*video.VideoList{}
	for _, m := range Video {
		videos = append(videos, &video.VideoList{
			UserId: int32(m.UserId),
			Url:    m.Url,
		})
	}
	return &video.VideoListResp{List: videos}, nil
}
